package com.xyw.code.authentication.server.service.impl;

import com.xyw.code.authentication.server.service.IAuthenticationService;
import com.xyw.code.authentication.server.service.IMenuService;
import com.xyw.code.authentication.server.util.SecurityUtil;
import com.xyw.code.authorization.common.entity.constant.SecurityConstant;
import com.xyw.code.authorization.common.entity.vo.SecurityUser;
import com.xyw.code.authorization.common.entity.vo.SysMenu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xuyiwei
 * Date: 2020/3/5
 * Time: 下午1:58
 * Email: 1328312923@qq.com
 * Description: No Description
 **/
@Service
@Slf4j
public class AuthenticationServiceImpl implements IAuthenticationService {

    @Autowired
    private IMenuService menuService;

    @Override
    public boolean decide(HttpServletRequest authRequest) {
        log.info("url:{},method:{}",authRequest.getServletPath(),authRequest.getMethod());
        ConfigAttribute configAttribute =  menuService.findConfigAttributesByUrl(authRequest);
        //得到用户所拥有的的权限
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SecurityUser securityUser = SecurityUtil.getUser(authentication);
        List<SysMenu> sysMenus = queryByUsername(securityUser.getUsername());
        return isMatch(sysMenus,configAttribute);
    }

    private boolean isMatch(List<SysMenu> sysMenus, ConfigAttribute configAttribute) {
        if(SecurityConstant.NONEXISTENT_URL.equals(configAttribute.getAttribute())){
            return true;
        }
        return sysMenus.stream().anyMatch(sysMenu -> {
            if(sysMenu!=null && sysMenu.getPerms()!=null && sysMenu.getPerms().equals(configAttribute.getAttribute())){
                return true;
            }
            return false;
        });
    }

    private List<SysMenu> queryByUsername(String username) {
        return menuService.queryByUsername(username);
    }
}
